package com.ricky.utils;



import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpRequest;
import jdk.incubator.http.HttpResponse;
import jdk.incubator.http.MultiMapResult;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;

/**
 * Created by bgt on 2017/10/1.
 * Java9http示例
 * <p>
 * VM 参数中添加模块支持
 * --add-modules jdk.incubator.httpclient
 */
public class HttpUtils9 {
    // private static HttpClient client = HttpClient.newHttpClient();
    private static HttpClient client = null;

    static {
        //这里是httpclient的配置
        init();


    }

    public static void main(String[] args) {
        // HttpDemo.HttpGet();
        HttpUtils9.HttpGet2();
    }

    public static void init(){
        try {
            Authenticator authenticator=new Authenticator() {
            };
            client= HttpClient.newBuilder()
                    .authenticator(authenticator)//配置authenticator
                    .sslContext(SSLContext.getDefault())//配置 sslContext
                    .sslParameters(new SSLParameters())//配置 sslParameters
                    .proxy(ProxySelector.getDefault())//配置 proxy
                    .executor(Executors.newCachedThreadPool())//配置 executor
                    .followRedirects(HttpClient.Redirect.ALWAYS)//配置 followRedirects
                    .cookieManager(new CookieManager())//配置 cookieManager
                    .version(HttpClient.Version.HTTP_2)//配置 version
                    .build();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    /**
     * 普通get方式
     *
     *
     * 结果:{
     "msg" : "未查询到用户,请认真检查账户或者是否登录",
     "success" : false
     }
     响应码:200

     */
    public static void HttpGet() {

        HttpRequest request = HttpRequest
                //.newBuilder(URI.create("http://blog.csdn.net/u014042066"))
                .newBuilder(URI.create("http://www.rqbao.com/lotteryAward/gettenrecordlist"))
                .header("refer", "http://www.oschina.com")//携带的参数
                .header("userId", "d3e750db32004972b0ae58f8129f50fc")
                .timeout(Duration.ofSeconds(2))//2秒过期
                .GET()
                .build();
        getReponse(request);

    }

    public static void HttpGet2() {

        HttpRequest request = HttpRequest
                //.newBuilder(URI.create("http://blog.csdn.net/u014042066"))
                .newBuilder(URI.create("http://www.rqbao.com/lotteryAward/gettenrecordlist"))
                .header("refer", "http://www.oschina.com")//携带的参数
                .header("userId", "d3e750db32004972b0ae58f8129f50fc")
                .timeout(Duration.ofSeconds(2))//2秒过期
                .GET()
                .build();
        getAsyReponse2(request);
    }

    /**
     * 文件上传
     */
    public static void HttpPost() {
        try {
            HttpRequest request = HttpRequest
                    .newBuilder(URI.create("http://blog.csdn.net/u014042066"))
                    .header("refer", "http://www.oschina.com")
                    .POST(HttpRequest.BodyProcessor.fromFile(Paths.get("/url.txt")))
                    .build();
            getAsyReponse(request);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    /**
     * 携带参数
     */
    public static void HttpPost2() {
        HttpRequest request = HttpRequest
                .newBuilder(URI.create("http://blog.csdn.net/u014042066"))
                .header("refer", "http://www.oschina.com")
                .POST(HttpRequest.BodyProcessor.fromString("name=ricky,pwd=123456"))
                .build();
        getReponse(request);
    }

    /**
     * 输出响应结果
     * @param request
     * @throws IOException
     * @throws InterruptedException
     */
    public static void getReponse(HttpRequest request) {
        HttpResponse<String> response = null;
        try {
            if (client==null) {
                init();
            }
            response = client.send(request, HttpResponse.BodyHandler.asString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String result = response.body();
        int code = response.statusCode();
        if (code == 200) {
            System.out.println("结果:" + result);
        }
        System.out.println("响应码:" + code);
    }

    /**
     * 输出响应结果 带path形式
     * @param request
     * @throws IOException
     * @throws InterruptedException
     */
    public static void getReponsePath(HttpRequest request) {
        HttpResponse<Path> response = null;
        try {
            client.send(request, HttpResponse.BodyHandler.asFile(Paths.get("/url.text")));
            Path body = response.body();
            System.out.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 输出响应结果 带path形式的异步
     * @param request
     * @throws IOException
     * @throws InterruptedException
     */
    public static void getAsyReponsePath(HttpRequest request) {
        CompletableFuture<Path> response = null;
        client
                .sendAsync(request, HttpResponse.BodyHandler.asFile(Paths.get("/url.text")))
                .thenApply((response1) -> response1.body());

        response.join();
    }

    /**
     * 异步的输出响应结果
     * @param request
     * @throws IOException
     * @throws InterruptedException
     */
    public static void getAsyReponse(HttpRequest request) {
        CompletableFuture<HttpResponse<String>> cf;
        cf = client.sendAsync(request, HttpResponse.BodyHandler.asString());
        HttpResponse<String> response = cf.join();
        System.out.println(response.body());
    }
    /**
     * 异步的输出响应结果
     * @param request
     * @throws IOException
     * @throws InterruptedException
     */
    public static void getAsyReponse2(HttpRequest request) {
        MultiMapResult<String> ress;
        ress = client.sendAsync(request, HttpResponse.MultiProcessor.asMap((req)-> Optional.of(
                HttpResponse.BodyHandler.asString()
        ))).join();
        ress.forEach((req,cf)->{
            HttpResponse<String> resp=cf.join();
            System.out.println("uri:"+resp.uri()+"---body:"+resp.body());
        });

    }
}
